<?php
define('ROOT_PATH',  str_replace('\\', '/', dirname(dirname(dirname(dirname(__FILE__)))))."/");
ini_set('date.timezone','Asia/Shanghai');
// error_reporting(E_ERROR);

require_once(ROOT_PATH."lib/db_init.php");//引入数据库文件
require_once(ROOT_PATH."lib/lib_base.php");
require_once(ROOT_PATH."lib/lib_safe.php");
require_once(ROOT_PATH."sdk/recharge_sdk.php");//麦流量
require_once(ROOT_PATH."sdk/suxun_sdk.php");//速讯
require_once(ROOT_PATH."application/constant/Constant.php");

require_once ROOT_PATH. "application/www/pay/lib/WxPay.Api.php";
require_once ROOT_PATH. "application/www/pay/lib/WxPay.Notify.php";
require_once ROOT_PATH. 'application/www/pay/example/log.php';

global $db;

echo 1111;
//初始化日志
$logHandler= new CLogFileHandler("logs/notify_".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}
	
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
		Log::DEBUG("call back:" . json_encode($data));
		$notfiyOutput = array();
		
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		
		$outTradeNo = $data["out_trade_no"];
		$openid = $data["openid"];
		
		global $db;
		
		$nowTime = date("Y-m-d H:i:s");
		$order = $db->getRow("select * from mb_order where out_trade_no = '$outTradeNo' and openid = '$openid'");
		if($order && $order["status"] < "1") {
			Log::DEBUG("status :" . $order["status"] . " update order data");
			
			$totalFee = $data["total_fee"];
			$db->query("update mb_order set status = '1' , total_fee = '$totalFee', update_time = '$nowTime' where id = " . $order["id"]);
			
			//判断实际支付价格是否一致
	/*     	if($totalFee < $order["bonues_price"] * 100) {
				Log::DEBUG("fail order, orderId :" . $order["id"] );
				return true;
			} else {
				Log::DEBUG("success order, chongzhiing");
			} */
			
			//查询后台配置的流量接口  1.麦流量  2.速迅
			$setting = $db->getRow("select liuliang from " . table("setting"));
			$liuliang=$setting['liuliang'];
			if($liuliang=='1'){
			    //麦流量 充值 开始
			    if (!$order["mai_status_code"]) {
			        $m = new FlowRecharge();
			        $req = $m->request($order["phone"],
			            $order["mb_value"] * 1024,
			            'chongzhi' . $order["mb_value"] . "Mb",
			            0,
			            $outTradeNo,
			            "http://www.chipshare.cn/ego/application/www/pay/recharge_notify.php");
			        Log::DEBUG("chongzi msg: $req");
			        $datas = json_decode($req, true);
			        if($datas["statusCode"] == 200) {
			            // 充值成功，设置充值状态
			            $sql = "update " . table("order") . " set type=1, mai_status_code = '" . $datas["data"]["status"] . "' , mai_price = '" . $datas["data"]["price"] . "', update_time = '$nowTime'";
			            if($datas["data"]["status"] == "0000") {
			                $sql .= ", status = '" . ORDER_STATUS::CHONGING . "' ";
			            } else {
			                $sql .= ", status = '" . ORDER_STATUS::FAIL . "' ";
			            }
			    
			            $sql .= " where id = " . $order["id"];
			    
			            $db->query($sql);
			        }else{
			            $code="m:".$datas['data']["orderId"].";";
			            //测试是否走到这里..
			            $db->query("update mb_order set status = '11' ,mobile_type='$code', total_fee = '$totalFee', update_time = '$nowTime' where id = " . $order["id"]);
			        }
			    }else{
			        //测试是否走到这里..
			        $db->query("update mb_order set status = '11' ,mobile_type='czfalse', total_fee = '$totalFee', update_time = '$nowTime' where id = " . $order["id"]);
			    }
			    return true;
			//麦流量 充值 结束
			}elseif($liuliang=='2'){
			    //速讯流量充值开始
			    if (!$order["mai_status_code"]) {
			        $s = new SxRecharge();
			        //根据product查询他的packageid
			        $product_id=$order['product_id'];
			        $productInfo=$db->getRow("select * from mb_product where id=$product_id");
			        $packageid=$productInfo["packageid"];
			        $param['mobiles']=$order["phone"];
			        $param['packageid']=$packageid;
			        $req =$s->request_get($param);
			        Log::DEBUG("chongzi msg: $req");
			        $datas = $req;
			        if($datas["code"] ==0) {//status 0未支付 1已支付 2充值中  9已完成 11充值失败
			            // 充值成功，设置充值状态
			            $sql = "update " . table("order") . "   set status='9',type=2,mai_status='1', mai_order_id='".$datas['data']['orderid']."' , mai_status_code = '0000' , mai_price = '" . $datas["data"]["price"] . "', mai_succ_time='$nowTime',update_time = '$nowTime'";
			            $sql .= " where id = " . $order["id"];
			            $db->query($sql);
			        }else{
			            //充值失败，设置失败原因
			            $code="message:".$datas["message"];
			            //测试是否走到这里..
			            $db->query("update mb_order set status = '11' ,mai_fail_reason='$code', total_fee = '$totalFee', update_time = '$nowTime' where id = " . $order["id"]);
			        }
			    }else{
			        //测试是否走到这里..
			        $db->query("update mb_order set status = '11' ,mobile_type='czfalse', total_fee = '$totalFee', update_time = '$nowTime' where id = " . $order["id"]);
			    }
			    return true;
			    
			    //速讯流量充值结束
			}
		//充值流量结束
		} 
		return false;
	}
}

Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle(false);
